package cacco.jp.mld;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ReportAsSingleViolation;

import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cacco.jp.mld.panel.entity.UrlEntity;
import cacco.jp.mld.panel.form.JqgridResponse;
import cacco.jp.mld.panel.form.StatusResponse;
import cacco.jp.mld.panel.service.UrlService;
import cacco.jp.mld.panel.util.StringUtil;

@Controller
@RequestMapping(value = "/urls")
public class UrlController {
	private static final Logger logger = LoggerFactory
			.getLogger(UrlController.class);

	@Autowired
	private UrlService urlService;

	@RequestMapping(method = RequestMethod.GET)
	public String listHome(ModelMap map, HttpServletRequest request) {
		map.addAttribute("employee", new UrlEntity());
		map.addAttribute("list_url", urlService.getAll());
		UrlEntity entity = (UrlEntity) request.getSession().getAttribute("aa");
		map.addAttribute("session", entity);
		System.out.println(entity);

		return "url/urls";
	}

	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public JqgridResponse<UrlEntity> listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order,
			@RequestParam("_search") Boolean search) {

		logger.info("Listing items for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing items for grid with sort: {}, order: {}", sortBy,
				order);

		List<UrlEntity> list = null;
		list = urlService.getAlByPage(rows, page, sortBy, order);
		JqgridResponse<UrlEntity> response = new JqgridResponse<UrlEntity>();
		int totalRecords = urlService.getTotalRecords();
		int total = totalRecords % rows == 0 ? (int) Math.ceil(totalRecords
				/ rows) : (int) Math.ceil(totalRecords / rows) + 1;

		logger.info("Listing urls for grid with total rows {}", list.size());
		response.setRecords(list);
		response.setTotalRecords(totalRecords);
		response.setTotalPages(total);
		response.setCurrentPage(page);
		return response;
	}

	@RequestMapping(value = "/add", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	StatusResponse create(
			@RequestParam ("type") int type, @RequestParam ("status") int status,
			@RequestParam ("limitCheck") long limitCheck, @RequestParam ("errorTimes") int errorTimes,
			@RequestParam ("timeCreate") String timeCreate, @RequestParam ("timeUpdate") String timeUpdate,
			@RequestParam ("schedule ")String schedule) {
		UrlEntity url = new UrlEntity(type, status, limitCheck, errorTimes,
				timeCreate, timeUpdate, schedule);
		StatusResponse response = new StatusResponse();
		try {
			urlService.addUrl(url);
			response.setSuccess(true);
			logger.info("Added new url: {}", url.getId());
		} catch (Exception e) {
			response.setSuccess(true);
			logger.info("Added url failed");
		}
		
		
		return new StatusResponse(true);
	}

	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	@ResponseBody
	public StatusResponse update(@RequestBody UrlEntity url) {
		StatusResponse respone = new StatusResponse();
		url.setTimeUpdate(StringUtil.date2string(new Date()));
		try {
			urlService.updateUrl(url);
			respone.setSuccess(true);
			logger.info("Updated url: {}", url.getId());
		} catch (Exception e) {
			respone.setSuccess(false);
			respone.setMessage("This url is not exists");
			logger.info("Url is not exists: {}", url.getId());
		}
		return respone;
	}

	@RequestMapping(value = "/delete", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	StatusResponse delete(@RequestParam Integer id) {
		StatusResponse response = new StatusResponse();
		try {
		urlService.deleteUrl(id);
		logger.info("Deleted url: {}", id);
		} catch (Exception e) {
			response.setSuccess(false);
			logger.info("Delete failed");
		}
		return response;
	}

}
